package com.luoying.itew.activity;

import android.app.Application;
import android.content.SharedPreferences;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableBoolean;
import androidx.databinding.ObservableField;
import androidx.lifecycle.AndroidViewModel;

import com.luoying.itew.common.AntaiApplication;
import com.luoying.itew.common.SharedConfig;
import com.luoying.itew.http.BaseMap;
import com.luoying.itew.http.BaseResponse;
import com.luoying.itew.http.HttpRequestUtils;
import com.luoying.itew.http.rxjava.BaseHttpObserver;
import com.luoying.itew.http.rxjava.RxTransformerHelper;
import com.luoying.itew.manage.UserManage;
import com.luoying.itew.util.AesUtil;
import com.luoying.itew.util.DateFormatUtils;
import com.luoying.itew.util.SharedUtils;
import com.luoying.itew.util.UserUtils;

import java.util.Date;
import java.util.Map;


public class LoginViewModel extends AndroidViewModel   {

    /**
     * UI交互
     */
    public final UIChangEvent uiChangEvent = new UIChangEvent();

    /**
     * UI数据
     */
    public final ViewStyle viewStyle = new ViewStyle() ;

    public void init(){
        viewStyle.getLoginName().set(SharedUtils.getUserAccount());
        viewStyle.getSaveName().set(SharedUtils.isKeepAccount());
        viewStyle.getLoginPwd().set(SharedUtils.getUserPwd());
        viewStyle.getAutoLogin().set(SharedUtils.isKeepPwd());
    }

    public void startLogin(){
        BaseMap baseMap = new BaseMap()
                .put("uuid", AntaiApplication.android_id)
                .put("username", viewStyle.getLoginName().get())
                .put("password", viewStyle.getLoginPwd().get())
                .put("grant_type","password");
        baseMap.remove("access_token");
        //展示对话框
        uiChangEvent.showDialog.setValue("");
        HttpRequestUtils.getInstance().getRxAppApi()
                .userLogin(baseMap)
                .compose(RxTransformerHelper.observableIO2Main())
                .subscribe(new BaseHttpObserver<Map>() {

                    @Override
                    protected void onSuccess(BaseResponse<Map> baseResponse) {
                        saveLoginState(baseResponse.getResultEntity());
                        uiChangEvent.viewToActivity.setValue(true);
                    }

                    @Override
                    protected void onFailure(String errorMessage) {
                        uiChangEvent.dismissDialog.setValue(null);
                        uiChangEvent.showToast.setValue(errorMessage);
                    }

                    @Override
                    protected void onRequestEnd() {
                        super.onRequestEnd();
                        uiChangEvent.dismissDialog.setValue(null);
                    }
                });

    }


    private void saveLoginState(Map map){
        String token = String.valueOf(map.get(BaseMap.TOKEN));
        //保存token
        UserManage.getInstance().saveUserToken(token);
        UserUtils.setAccess_tokem(token);
        //更新自己的UUID
        HttpRequestUtils.getInstance().updateUUid();
        SharedPreferences shared = SharedUtils.getShared();
        SharedPreferences.Editor editor = shared.edit();
        boolean isKeepAccount = viewStyle.getSaveName().get();
        boolean isAuthLogin = viewStyle.getAutoLogin().get();
        //保存帐号记录状态
        editor.putBoolean(SharedConfig.SHARED_IS_KEEP_ACCOUNT,isKeepAccount );
        //保存登录状态
        editor.putBoolean(SharedConfig.SHARED_IS_KEEP_PWD, isAuthLogin);
        //保存帐号
        editor.putString(SharedConfig.SHARED_USER_ACCOUNT, isKeepAccount ? viewStyle.getLoginName().get() : "");
        //保存密码
        editor.putString(SharedConfig.SHARED_USER_PWD, isKeepAccount&&isAuthLogin ? viewStyle.getLoginPwd().get() : "");
        //保存sign
        String timestramp = DateFormatUtils.format(new Date());
        String sign = "";
        try {
            sign = AesUtil.byteArrayToHexString(AesUtil.encryptByAes(timestramp));
        } catch (Exception e) {
            e.printStackTrace();
        }
        editor.putString(SharedConfig.SHARED_USER_SIGN,isAuthLogin&&isKeepAccount?sign:"");
        editor.apply();
    }



    public LoginViewModel(@NonNull Application application) {
        super(application);
    }

    public static class ViewStyle{

        /**
         * 登录账户
         */
        private ObservableField<String> loginName = new ObservableField();
        /**
         * 登录密码
         */
        private ObservableField<String> loginPwd = new ObservableField();
        /**
         * 保存帐号
         */
        private ObservableBoolean saveName = new ObservableBoolean();
        /**
         * 自动登录
         */
        private ObservableBoolean autoLogin = new ObservableBoolean();

        public ObservableField<String> getLoginName() {
            return loginName;
        }

        public ObservableField<String> getLoginPwd() {
            return loginPwd;
        }

        public ObservableBoolean getSaveName() {
            return saveName;
        }

        public ObservableBoolean getAutoLogin() {
            return autoLogin;
        }

    }




}
